import Schemas from '../schemas';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

const ChannelApps = new Mongo.Collection('channelApps');

ChannelApps.attachSchema(Schemas.ChannelApp);

if (Meteor.isServer) {
  Meteor.publish('channel.has.app', function(appId, channelId) {
    return ChannelApps.find({
      appId: appId,
      channelId: channelId
    });
  });
}

const hasApp = (appId, channelId) => {
  check(appId, String);
  check(channelId, String);

  if (Meteor.isClient) {
    Meteor.subscribe('channel.has.app', appId, channelId);
  }

  const result = ChannelApps.find({
    appId: appId,
    channelId: channelId
  });

  if (result && result.count() === 1) {
    return true;
  } else {
    return false;
  }
};

export { ChannelApps, hasApp };